package com.sy.cloud.guess.controller;

import com.alibaba.fastjson.JSONObject;
import com.gok.pay.wx.WXPayUtil;
import com.google.gson.Gson;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import com.sy.cloud.guess.model.*;
import com.sy.cloud.wechat.model.Wxuser;
import com.sy.common.model.Juejinuser;
import com.sy.common.persistence.QueryHelper;
import com.sy.common.service.*;
import com.sy.common.util.Funutil;
import com.sy.shiro.UsernameToken;
import lombok.extern.slf4j.Slf4j;
import net.glxn.qrgen.core.AbstractQRCode;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.impl.client.SystemDefaultCredentialsProvider;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by mac on 2017-10-23.
 */
@Controller
@RequestMapping("/trade")
@Slf4j
public class TradeController {

    @Resource
    private IDbService dbService;

    @Resource
    private IBaseService baseService;

    @Resource
    private ITestService testService;

    //    @Resource
//    private ISetsService sets;
    @Resource
    private IAlgorithm algorithm;


    @Resource
    private CashoutController cashoutController;

    @Resource
    private CookieController cookieController;

    /**
     * 走势图数据
     */
    @RequestMapping(value = "/trendchart", method = RequestMethod.GET)
    public
    @ResponseBody
    void index(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setLocale(new java.util.Locale("zh", "CN"));
        QueryHelper queryHelper = new QueryHelper();
        queryHelper.setLimit(10);
        queryHelper.setOffset(0);
        String sql = "select sp_gokguess_num.*, sp_hero_set.name from sp_gokguess_num left join sp_hero_set on sp_gokguess_num.heroId = sp_hero_set.id ORDER BY sp_gokguess_num.id DESC limit 0,10";
        List<Object[]> goklist = baseService.nativeQuery(sql);
        Gson gson = new Gson();
        String json = gson.toJson(goklist);
        log.info(json);
        response.getWriter().print(json);
//        return json;
    }

    /**
     * 英雄中奖结果设定
     * 每到设定的时间间隔，就运行一次，结果存在数据库里
     * 传入参数：期号
     */
    @RequestMapping(value = "/dealhero", method = RequestMethod.GET)
    public
    @ResponseBody
    String hero(HttpServletRequest request) {

        String s4 = testService.getNowIssue();
        log.info("计算出来的最大期号"+s4);

        int max = 10000;
        long result = 1;
        Random random = new Random();
        int s = random.nextInt(max);
        List<Heroset> herosetList = testService.getList();
        if (s <= herosetList.get(0).getPercent() * 100) {
            herosetList.get(0).getId();
        } else if (s > herosetList.get(0).getPercent() * 100 && s <= (herosetList.get(0).getPercent() * 100 + herosetList.get(1).getPercent() * 100)) {
            result = herosetList.get(1).getId();
        } else if (s >= 3648 && s < 5472) {
            result = herosetList.get(2).getId();
        } else if (s >= 5472 && s < 6688) {
            result = herosetList.get(3).getId();
        } else if (s >= 6688 && s < 7904) {
            result = herosetList.get(4).getId();
        } else if (s >= 7904 && s < 8816) {
            result = herosetList.get(5).getId();
        } else if (s >= 8816 && s < 9728) {
            result = herosetList.get(6).getId();
        } else if (s >= 9728 && s < 9910) {
            result = herosetList.get(7).getId();
        } else if (s >= 9910 && s < 10000) {
            result = herosetList.get(8).getId();
        }
        // 获得英雄场的结果

        // 使用事物 更新 sp_juejin_order表里的status为0的订单
        //

        Gokguessnum gokguessnum2 = algorithm.kongpancode("1");// 获得精确场的中奖结果


        gokguessnum2.setIssue(Integer.parseInt(s4));// 期号
        gokguessnum2.setHeroId(Integer.parseInt(gokguessnum2.getOpencode().substring(gokguessnum2.getOpencode().length() - 1, gokguessnum2.getOpencode().length())));// 中奖的英雄，qq在线人数的最后一位数

        // 更新订单表里的订单和缓存金额
        testService.updateGokguessnum(gokguessnum2);
        return result + "";
    }


    /**
     * 英雄场下注和精确场下注，下订单的接口 下单时的手续费20%体现在赔率上
     */
    @RequestMapping(value = "/placeorder1", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public
    @ResponseBody
    JSONObject placeorder1(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        String type = request.getParameter("type");
        if( type == null ){
            type = "1";
        }

        JSONObject resultObject = new JSONObject();
        // 获取用户信息
        UsernameToken token = testService.getUser();

        if( token == null ){
            resultObject.put("status", "0");
            resultObject.put("message", "no login");
            return resultObject;
        }
        Double sumamount = 0.0;// 下单的和

        // 先获取参数
        String para1 = request.getParameter("para");
        String[] source = para1.split("-");
        Map<Integer,Integer> mapBet = new HashMap<Integer,Integer>(); // 用来下注数据的map
        for (int i = 0; i < source.length; i++) {
            String[] detail = source[i].split(",");
            sumamount += Integer.parseInt(detail[1]);
            mapBet.put( Integer.parseInt(detail[0]), Integer.parseInt(detail[1]));
            if( Integer.parseInt(detail[1]) > 1000 ){
                resultObject.put("status", "0");
                resultObject.put("message", "投注超出上限");
                return resultObject;
            }
        }

        // 查询用户的余额
        Double money = testService.getMoney(token.getPhone());
        if (sumamount > money) {
            // 下单金额大于余额
            resultObject.put("status", "0");
            resultObject.put("message", "下单金额大于余额");
            return resultObject;
        }

        // 判断这个用户这一期下注金额，每一个选择，有没有超过5000coin
        String issue = testService.getNowIssue();
        String sql ="select sum(amount) as amo,capital from sp_juejin_order where issue = "+issue+" and userid = "+token.getUserId()+" group by capital";
        List<Object[]> list = baseService.nativeQuery(sql);
        if( list.size() > 0 ){
            for( int i = 0 ; i < list.size(); i++ ){
                Object[] objects = list.get(i);
                if( mapBet.containsKey( Integer.parseInt(objects[1].toString()) ) ){
                    // 历史总余额和这次下单的相加，超过5000，驳回
                    if(  Integer.parseInt(objects[0].toString()) + mapBet.get( Integer.parseInt(objects[1].toString())) > 5000 ){
                        resultObject.put("status", "0");
                        resultObject.put("message", "投注超出上限");
                        return resultObject;
                    }
                }
            }
        }



        List<Heroset> herosetList = new ArrayList<Heroset>();
        StringBuilder selectSql0 = new StringBuilder();
        selectSql0.append(" From Heroset u where type = ").append(type);
        herosetList = baseService.listQuery(selectSql0.toString(), Heroset.class);
        Map<Integer, Double> odsMap = new HashMap<Integer, Double>();
        if( type.equals("1") ){
            odsMap = testService.oddsSet("hero");
        }else if( type.equals("2") ){
            odsMap = testService.oddsSet("digit");
        }
        List<JOrder> orderList = new ArrayList<JOrder>();
        for (int i = 0; i < source.length; i++) {
            String[] detail = source[i].split(",");
            JOrder order = new JOrder();
            order.setCreatetime(System.currentTimeMillis() / 1000 + "");
            order.setPhone(token.getPhone());// 用户电话号码
            order.setUserid(token.getUserId());// 用户id
            order.setAmount(Integer.parseInt(detail[1]));// 下单金额
            order.setCapital(Integer.parseInt(detail[0]));// 英雄的种类
            order.setIs_win(0);
            log.info(source[i]);
            Gson gson = new Gson();
            log.info(gson.toJson(odsMap));
            log.info(odsMap.get(detail[0]) + "");
            order.setGet_amount(Integer.parseInt(detail[1]) * odsMap.get( Integer.parseInt(detail[0])) );// 赢了应该获得的金额
            order.setTrade_time(35); //默认35秒
            order.setType(0);
            orderList.add(order);
        }
        if (testService.dealdb(orderList)) {// 增加sp_juejin_order表的记录
            // 下单成功，扣除用户余额
            Juejinuser juejinuser = testService.getJueUserByPhone(token.getPhone());
            juejinuser.setCoin(juejinuser.getCoin() - sumamount);
            juejinuser.setMoney( juejinuser.getMoney() - sumamount/juejinuser.getRatio() );
            // 结算时增加3张奖券和一颗星
            testService.updateUser(juejinuser);

            // 手续费给会员单位，和运营中心，和总平台
            if( juejinuser.getToken() != null && juejinuser.getToken() != "" ){
                testService.calcFeeForUser( juejinuser.getToken(), sumamount/juejinuser.getRatio() ); // 人民币
            }


            if (juejinuser.getShareid() != null) {
                if (juejinuser.getShareid() != 0) {
                    // 一级用户
                    Juejinuser juejinuser1 = testService.getJueUserById(juejinuser.getShareid() + "");
                    if (juejinuser1 != null) {
                        juejinuser1.setFanlimoney(juejinuser1.getFanlimoney() + Math.round(sumamount * 5) * 0.001d);// 金币
                        // 二级用户
                        if (juejinuser1.getShareid() != 0) {
                            Juejinuser juejinuser2 = testService.getJueUserById(juejinuser1.getShareid() + "");
                            if (juejinuser2 != null) {
                                juejinuser2.setFanlimoney(juejinuser2.getFanlimoney() + Math.round(sumamount * 3) * 0.001d);
                                // 三级用户
                                if (juejinuser2.getShareid() != 0) {
                                    Juejinuser juejinuser3 = testService.getJueUserById(juejinuser2.getShareid() + "");
                                    juejinuser3.setFanlimoney(juejinuser3.getFanlimoney() + Math.round(sumamount * 1) * 0.001d);
                                }
                            }
                        }
                    }
                }
            }



            // 判断这次下单有没有获得背包里的英雄卡
            JSONObject jsonObject = testService.getKnapsackWinHero( juejinuser.getId() );
            if( jsonObject != null ){
                if( jsonObject.containsKey( "winhero" ) ){
                    resultObject.put("status", "2");
                    resultObject.put("messages", "success");
                    resultObject.put("winhero", jsonObject.get("winhero"));
                }
            }
            resultObject.put("status", "1");
            resultObject.put("messages", "success");
        } else {
            resultObject.put("status", "0");
            resultObject.put("message", "数据库错误");
        }
        return resultObject;
    }


    @RequestMapping(value = "/capitallist", method = RequestMethod.GET)
    public
    @ResponseBody
    void getlist3(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setLocale(new java.util.Locale("zh", "CN"));
        Gson gson = new Gson();
        List<Object[]> allList = testService.getList3();
        String json = gson.toJson(allList);
        response.getWriter().print(json);
    }


    /**
     * 判断是否登录
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/iflogin", method = RequestMethod.GET)
    public
    @ResponseBody
    void getloginstatus(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取用户信息
        JSONObject jsonObject = new JSONObject();
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection pr = subject.getPrincipals();
        if (pr != null) {
            // 登录
            jsonObject.put("status", "1");
            response.getWriter().print(jsonObject.toString());
        } else {
            // 没登录
            jsonObject.put("status", "0");
            response.getWriter().print(jsonObject.toString());
        }
    }


    /**
     * 给出前端页面的倒计时
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/countdown", method = RequestMethod.GET)
    public
    @ResponseBody
    void getCountDown(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String str = "select max(create_time) from sp_gokguess_num";
        List<Object[]> objectList = baseService.nativeQuery(str);
        Object object = objectList.get(0);

        // object是上次计算的时间。
        double ob2 = Double.parseDouble(object.toString()) + 60;

        double ob3 = ob2 - System.currentTimeMillis() / 1000;

        response.getWriter().print((int) ob3);
    }

    /**
     * 给出前端页面的倒计时
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/countdown1", method = RequestMethod.GET)
    public
    @ResponseBody
    void getCountDown1(HttpServletRequest request, HttpServletResponse response) throws Exception {

        int ob3 = -31;
        response.getWriter().print(ob3);
    }


    /**
     * test
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public
    @ResponseBody
    String test(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return "test";
    }


    /**
     * 游戏结果
     */
    @RequestMapping(value = "/gameresult", method = RequestMethod.GET)
    public
    @ResponseBody
    void gameResult(HttpServletRequest request, HttpServletResponse response) {
        QueryHelper queryHelper = new QueryHelper();
        queryHelper.setOffset(0);
        queryHelper.setLimit(1);
        StringBuilder hql = new StringBuilder();
        hql.append("From Gokguessnum order by create_time desc");
        List<Gokguessnum> gokguessnumList = baseService.listQueryForPage(hql.toString(), Gokguessnum.class, queryHelper);


        Gokguessnum gokguessnum = gokguessnumList.get(0);
//        DecimalFormat df = new DecimalFormat("0");

        String jsonObject = JSONObject.toJSONString(gokguessnumList.get(0));
        try {
            response.getWriter().print(jsonObject);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 背包信息展示接口 密钥JLSfWRRoCt5idlsB    SHA1加密
     */
    @RequestMapping(value = "/knapsackEncry", method = RequestMethod.GET)
    public
    @ResponseBody
    JSONObject knapsack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        // 获取用户信息
        UsernameToken token = testService.getUser();
        if( token == null ){
            result.put("status", "0");
            result.put("message", "没有登录");
            return result;
        }


        String userid = token.getUserId()+"";
        String type = request.getParameter("type");
        if( type == null ){
            result.put("status", "0");
            result.put("message", "type参数必传");
            return result;
        }

        //  点击赠送时生成密文，明文 type=&userid=
        String express = "type="+type+"&userid="+userid+"JLSfWRRoCt5idlsB";
        String ciphertext = Funutil.encode( express );

        // 返回密文
        result.put("status", "1");
        result.put("message", ciphertext);
        return result;
    }


    @RequestMapping(value = "/knapsackdisplay", method = RequestMethod.GET)
    public
    @ResponseBody
    String knapsackdisplay(HttpServletRequest request, HttpServletResponse response) throws IOException {
        UsernameToken token = testService.getUser();
        if( token == null ){
            return "";
        }
        Juejinuser juejinuser = testService.getJueUserById( token.getUserId()+"" );
        return juejinuser.getKnapsack();
    }



    /**当用户点击赠送按钮时，发送这个链接给好友
     * 背包 增加卡片。加密信息,密钥JLSfWRRoCt5idlsB
     */
    @RequestMapping(value = "/knapsack", method = RequestMethod.GET)
    public
    String knapsackdisplay2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 朋友圈分享和好友分享
        String url = "";
        if( request.getQueryString() == null ){
            url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
        }else{
            url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI() + "?" + request.getQueryString();
        }
        long cur =  System.currentTimeMillis();
        Wxuser wxuser1 = testService.getWxByWxid( "gh_6dadebf53ec2" );//微信原始id
        Map<String, String> mapreq = new HashMap();
        String non = WXPayUtil.generateUUID();
        mapreq.put("noncestr", non);
        mapreq.put("jsapi_ticket", wxuser1.getTicket() );
        mapreq.put("timestamp", cur+"" );
        mapreq.put("url", url );
        String signStr = "";
        try {
            signStr = Funutil.generateSignature( mapreq );
        } catch (Exception e) {
            e.printStackTrace();
        }
        mapreq.put("signature", signStr );
        String gsond = new Gson().toJson(mapreq);
        request.setAttribute( "signPackage", gsond );

        UsernameToken token = testService.getUser();
        if( token == null ){
            request.setAttribute( "historyPage", "knapsack" );
            return "login";
        }
        Juejinuser juejinuser = testService.getJueUserById( token.getUserId()+"" );
        request.setAttribute( "nickname", juejinuser.getUsername() );
        request.setAttribute( "userid", juejinuser.getId() );
        request.setAttribute( "token", juejinuser.getToken() );

        return "bagview";
    }


        /**当用户点击赠送按钮时，发送这个链接给好友
         * 背包 增加卡片。加密信息,密钥JLSfWRRoCt5idlsB
         */
    @RequestMapping(value = "/knapsackadd", method = RequestMethod.GET)
    public
    String knapsackadd(HttpServletRequest request, HttpServletResponse response) throws IOException {


        String t0 = request.getParameter("type");
        String idFrom = request.getParameter("idfrom");
        String ciphP = request.getParameter("ciphP");

        if( ciphP == null || idFrom == null || t0 == null ){
            log.info("必传参数没有上送");
            return "index";
        }
        Integer herowin = Integer.parseInt(t0);


        // 获取用户信息
        UsernameToken token = new UsernameToken();
        token = testService.getUser();
        if( token == null ){
            // 用户没有登录 把赠送的英雄卡放到cookie缓存里面
            cookieController.addCookie(response, "knapsackadd", t0 );
            cookieController.addCookie(response, "knapsacksec", ciphP );
            // 登录之后返回英雄卡页面
            request.setAttribute( "historyPage", "knapsack" );
            return "login";
        }

        /*验证加密*/
        //  点击赠送时生成密文，明文 type=&userid=
        String express = "type="+t0+"&userid="+idFrom+"JLSfWRRoCt5idlsB";
        String ciphertext = Funutil.encode( express );
        if( !ciphertext.equals( ciphP ) ){
            log.info("用户"+token.getUserId()+"签名错误");
            return "index";
        }



        Juejinuser juejinuser = testService.getJueUserByPhone( token.getPhone() );
        if( juejinuser == null ){
            return "index";
        }

        KnapgiftRecord knapgiftRecord = testService.getKnaByUserType( idFrom, herowin.toString() );
        if( knapgiftRecord != null ){
            knapgiftRecord.setStatus(1);
            knapgiftRecord.setUserIdTo( juejinuser.getId().intValue() );
            knapgiftRecord.setSavetime( System.currentTimeMillis()/1000 );
            baseService.update( knapgiftRecord );
        }else if( knapgiftRecord == null ){
            log.info("英雄卡不能重复领取");
            return "index";
        }
        // 增加卡片
        if( !testService.KnapsackCardAdd( juejinuser, herowin, idFrom )){

        }

        return "index";
    }


    /**
     * 背包 减少卡片
     */
    @RequestMapping(value = "/knapsackdelete", method = RequestMethod.GET)
    public
    @ResponseBody
    JSONObject knapsackdelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        String t0 = request.getParameter("type");
        log.info("获得上传的参数"+t0+"===");
        if( t0 == null || t0 == "" ){
            result.put("status", "0");
            result.put("message", "你尚未选定要赠送的英雄卡");
            return result;
        }
        Integer herowin = Integer.parseInt(t0);

        // 获取用户信息
        UsernameToken token = testService.getUser();
        if( token == null ){
            result.put("status", "0");
            result.put("message", "未登录");
            return result;
        }

        Juejinuser juejinuser = testService.getJueUserByPhone( token.getPhone() );
        if( juejinuser == null ){
            result.put("status", "0");
            result.put("message", "未登录");
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return result;
        }

        // 减少卡片
        String kre = testService.KnapsackCardDelete( juejinuser, herowin );
        if( kre.equals("nocards") ){
            result.put("status", "0");
            result.put("message", "卡片数量不足");
            return result;
        }


        // 增加记录
        KnapgiftRecord knapgiftRecord = new KnapgiftRecord();
        knapgiftRecord.setStatus(0);
        knapgiftRecord.setType( herowin );
        knapgiftRecord.setCreatetime( System.currentTimeMillis()/1000 );
        knapgiftRecord.setUserIdFrom( juejinuser.getId().intValue() );
        baseService.update(knapgiftRecord);


        result.put("status", "1");
        result.put("message", "success");
        return result;
    }

    /**
     * 验证码
     * @param request
     * @param response
     * @param model
     * @throws Exception
     */
    @RequestMapping(value = "/vericode", method = RequestMethod.GET)
    public
    @ResponseBody
    void vericode(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {


        UsernameToken juejinuser = testService.getUser();

        int a = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;//产生1000-9999的随机数
        request.getSession().setAttribute("vericode", a);
        log.info("发送出去的验证码是"+a);

        String phone = "";

        if (juejinuser == null) {
            phone = request.getParameter("phone");
        } else {
            phone = juejinuser.getPhone();
        }

        Funutil.send_newsms(phone, a + "");

    }

    /**
     * 订单列表
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/orderList", method = RequestMethod.GET)
    public void ordreList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取用户信息
        UsernameToken token = testService.getUser();
        if (token != null) {
        } else if( token == null ) {
            // 没有登录
            response.getWriter().print("no login");
            return;
        }

        String p1 = request.getParameter("page");// 第几页
        if (p1 == null) {
            p1 = "0";
        }
        int p2 = Integer.parseInt(p1);


        QueryHelper queryHelper = new QueryHelper();
        queryHelper.setLimit(p2 * 20 + 1);// (p2-1)*20+1
        queryHelper.setLimit((p2 + 1) * 20);// (p2-1)*20+1


        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From JOrder where userid = ");
        stringBuilder.append(token.getUserId());
        stringBuilder.append(" order by id desc");
        Gson gson = new Gson();
        log.info(stringBuilder.toString());
        List<JOrder> orderList = baseService.listQueryForPage(stringBuilder.toString(), JOrder.class, queryHelper);
        response.getWriter().print(gson.toJson(orderList));
    }

    /**
     * 开宝箱
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/chestOpen", method = RequestMethod.GET)
    public void chestOpen(HttpServletRequest request, HttpServletResponse response) throws IOException {
        UsernameToken usertoken = testService.getUser();
        /*
        * 开宝箱随机送20到30个金币
        * */
        Random random = new Random();
        int reward1 = 20 + random.nextInt(10);
        double reward = reward1 + random.nextInt(10) / 10 + random.nextInt(10) / 100;
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("From Juejinuser where phone =");
        stringBuffer.append(usertoken.getPhone());
        Juejinuser juejinuser = baseService.queryObject(stringBuffer.toString(), Juejinuser.class);
        juejinuser.setStar(0);

        juejinuser.setCoin(juejinuser.getCoin() + reward);

        juejinuser.setMoney( juejinuser.getMoney() + reward/juejinuser.getRatio() );

        testService.updateUser(juejinuser);
        // 输出奖励的金币
        response.getWriter().print(reward);
    }

    /**
     * 生成二维码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/qrcode", method = RequestMethod.GET)
    public void qrcode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        UsernameToken usertoken = testService.getUser();

        if( usertoken == null ){
            return;
        }

        String url = "";
        if( request.getSession().getAttribute("token") == null ){
            Juejinuser juejinuser = testService.getJueUserById( usertoken.getUserId().toString() );
            if( juejinuser != null ){
                if( juejinuser.getToken() != null ){
                    log.info("1");
                    url = request.getScheme() + "://" + request.getServerName()+"?shareid="+usertoken.getUserId()+"&token="+juejinuser.getToken();
                }else{
                    log.info("1");
                    url = request.getScheme() + "://" + request.getServerName()+"?shareid="+usertoken.getUserId();
                }
            }else{
                log.info("1");
                url = request.getScheme() + "://" + request.getServerName()+"?shareid="+usertoken.getUserId();
            }

        }else{
            log.info("1");
            String token = request.getSession().getAttribute("token").toString();
            url = request.getScheme() + "://" + request.getServerName()+"?shareid="+usertoken.getUserId()+"&token="+token;
        }
        log.info("生成二维码的地址是"+url);
        AbstractQRCode qrCode = QRCode.from( url );
        // 设置字符集，支持中文
        qrCode.withCharset("utf-8");
        // 设置生成的二维码图片大小
        qrCode.withSize(260, 260);
        ByteArrayOutputStream out = qrCode.to(ImageType.PNG).stream();


        File file = new File(request.getSession().getServletContext().getRealPath("/")+"/qrcode/"+usertoken.getUserId()+".png");
        file.setReadable(true, false);
        file.setWritable(true, false);
        file.setExecutable(true, false);
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(file);
            fout.write(out.toByteArray());
            fout.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fout.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 金币转换成礼品
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/coinToGift", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject coinToGift(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        GiftExchange giftExchange = new GiftExchange();

        UsernameToken usernameToken = testService.getUser();
        if( usernameToken == null ){
            result.put( "status", "0" );
            result.put( "message", "nologin" );
            return result;
        }

        String money = request.getParameter("money");
        if( money == null ){
            result.put( "status", "0" );
            result.put( "message", "money missing" );
            return result;
        }

        giftExchange.setMoney(Double.parseDouble(money));
        giftExchange.setStatus(0);
        giftExchange.setUserid(usernameToken.getUserId().intValue());
        giftExchange.setCreatetime( (int)(System.currentTimeMillis()/1000) );
        giftExchange.setUpdatetime( (int)(System.currentTimeMillis()/1000) );

        String resu = testService.addExchangeOrder(giftExchange);
        if( resu.equals("") ){
            result.put( "status", "1" );
            result.put( "message", "success" );
            return result;
        }else if(resu.equals("coin not enough")){
            result.put( "status", "0" );
            result.put( "message", resu );
            return result;
        }
        return result;
    }

    /**
     * 退货接口，礼物变成人民币
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/giftToMoney", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JSONObject giftToMoney(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 礼品id；

        JSONObject result = new JSONObject();

        String giftId = request.getParameter("giftId");
        for (int i = giftId.length(); --i > 0; ) {
            if (!Character.isDigit(giftId.charAt(i))) {
                response.getWriter().print("not digit");
                result.put("status", "0");
                result.put("message", "para not digit");
                return result;
            }
        }
        UsernameToken usernameToken = testService.getUser();
        if (usernameToken == null) {
            result.put("status", "0");
            result.put("message", "no login");
            return result;
        }

        // 判断是否有绑卡
        Juejinuser juejinuser = testService.getJueUserById(usernameToken.getUserId().toString());
        if (juejinuser.getIfbind() == 1) {
            // 有绑卡,直接创建提现订单 sp_juejin_tiorder
            TiOrder tiOrder = new TiOrder();
            tiOrder.setStatus(0);
            tiOrder.setUserid(usernameToken.getUserId());
            tiOrder.setGiftid( Integer.parseInt( giftId ) );
            GiftExchange giftExchange = testService.getGiftById(Integer.parseInt(giftId));
            giftExchange.setStatus( 1 );
            baseService.update( giftExchange );


            tiOrder.setPrice(giftExchange.getMoney() - 2);
            tiOrder.setPtmoney(giftExchange.getMoney());
            tiOrder.setCreatetime(System.currentTimeMillis() / 1000 + "");
            tiOrder.setIdnumber(juejinuser.getId_number());
            tiOrder.setCardnum(juejinuser.getCard_num());
            tiOrder.setWeixin(juejinuser.getReal_name());
            tiOrder.setOrdersn( "K"+Funutil.getOrdersn() );
            try {
                JSONObject jsonObject = cashoutController.cashoutAction(request, response, tiOrder);
                if( jsonObject.get("status").equals("1") ){
                    result.put("status", 1);
                }else{
                    result.put("status", 0);
                }
                result.put("message", jsonObject.get("message"));

                return result;
            } catch (Exception e) {
                e.printStackTrace();
                result.put("status", 0);// 系统错误
                result.put("message", "系统错误");
                return result;
            }


        } else if (juejinuser.getIfbind() == 0) {
            // 没有绑卡

            result.put("status", 2);// 提示是否需要绑卡
            result.put("message", "need bind card");
            return result;
        }
        result.put("status", 1);// 提示是否需要绑卡
        result.put("message", "success");
        return result;
    }


    /**
     * 礼品接口,所有礼品的列表
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/shopGiftList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JSONObject shopGiftList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List< Gift > gifts = baseService.listQuery("From Gift", Gift.class);
        JSONObject result = new JSONObject();
        result.put("status", "0");
        result.put("message", gifts);
        return result;
    }


    /**
    *佣金提现
    * */
    @RequestMapping(value = "/commission", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JSONObject commission(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject jsonObject = new JSONObject();

        String money0 = request.getParameter("money");
        double moneypt = Double.parseDouble( money0 );
        if( moneypt <= 12  ){
            jsonObject.put("status","1");
            jsonObject.put("message", "提现金额不可低于12元");
            return jsonObject;
        }
        double money = moneypt-2;


        UsernameToken usernameToken = testService.getUser();
        if( usernameToken == null ){
            jsonObject.put("status", "0");
            jsonObject.put("message", "nologin" );
            return jsonObject;
        }
        Juejinuser juejinuser = testService.getJueUserById( usernameToken.getUserId().toString() );

        TiOrder tiOrder = new TiOrder();
        tiOrder.setStatus(0);
        tiOrder.setUserid(usernameToken.getUserId());
        tiOrder.setType(1);// 佣金提现



        tiOrder.setPrice( money );
        tiOrder.setPtmoney( moneypt );
        tiOrder.setCreatetime(System.currentTimeMillis() / 1000 + "");
        tiOrder.setIdnumber(juejinuser.getId_number());
        tiOrder.setCardnum(juejinuser.getCard_num());
        tiOrder.setWeixin(juejinuser.getReal_name());
        tiOrder.setOrdersn( "K"+Funutil.getOrdersn() );

        try {
            cashoutController.cashoutAction(request, response, tiOrder);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("status", 0);// 系统错误
            jsonObject.put("message", "sys error");
            return jsonObject;
        }
        jsonObject.put("status", 1);// 系统错误
        jsonObject.put("message", "success");
        return jsonObject;
    }
}
